import os
from enum import Enum
from dataclasses import dataclass

from datetime_mcp_server.server import mcp
from datetime_mcp_server.logging_config import setup_logging

logger = setup_logging()


class TransportType(str, Enum):
    """Supported MCP server transport types."""

    STDIO = "stdio"
    HTTP = "http"
    SSE = "sse"

    @classmethod
    def values(cls) -> list[str]:
        """Get all valid transport values."""
        return [transport.value for transport in cls]


@dataclass
class MCPServerConfig:
    mcp_server_transport: TransportType = None
    mcp_bind_host: str = None
    mcp_bind_port: int = None

    def __post_init__(self):
        """Validate mcp configuration."""
        if self.mcp_server_transport is None:
            raise ValueError("MCP SERVER TRANSPORT is required")
        if self.mcp_server_transport not in TransportType:
            raise ValueError(f"Invalid transport: {self.mcp_server_transport}. "
                             f"Must be one of: {TransportType.values()}")

        if self.mcp_bind_host is None:
            raise ValueError("MCP BIND HOST is required")

        if self.mcp_bind_port is None:
            raise ValueError("MCP BIND PORT is required")
        if not (1 <= self.mcp_bind_port <= 65535):
            raise ValueError(f"Port must be between 1-65535, got {self.mcp_bind_port}")


mcp_config = MCPServerConfig(
        mcp_server_transport=TransportType(os.environ.get("DATETIME_MCP_SERVER_TRANSPORT", "http").lower()),
        mcp_bind_host=os.environ.get("DATETIME_MCP_BIND_HOST", "127.0.0.1"),
        mcp_bind_port=int(os.environ.get("DATETIME_MCP_BIND_PORT", "8001"))
)


def run_server():
    transport = mcp_config.mcp_server_transport
    http_transports = [TransportType.HTTP, TransportType.SSE]
    if transport in http_transports:
        logger.info("Starting Datetime MCP Server",
                    transport=transport,
                    host=mcp_config.mcp_bind_host,
                    port=mcp_config.mcp_bind_port)
        mcp.run(transport=transport, host=mcp_config.mcp_bind_host, port=mcp_config.mcp_bind_port)

    else:
        logger.info("Starting Datetime MCP Server", transport=transport)
        mcp.run(transport=transport)


if __name__ == "__main__":
    run_server()
